package com.umerclass.ui.user;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.SwitchCompat;
import androidx.core.content.FileProvider;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.facebook.drawee.view.SimpleDraweeView;
import com.umerclass.AppDroid;
import com.umerclass.R;
import com.umerclass.bean.user.Image;
import com.umerclass.frame.model.InfoResult;
import com.umerclass.frame.ui.activity.BaseActivity;
import com.umerclass.utils.Constants;
import com.umerclass.utils.file.FileUtils;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.PicassoEngine;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

public class UserCenterActivity extends BaseActivity {

    @BindView(R.id.linear_back)
    LinearLayout linearBack;
    @BindView(R.id.simpleDraweeView)
    SimpleDraweeView simpleDraweeView;
    @BindView(R.id.linear_head)
    LinearLayout linearHead;
    @BindView(R.id.linear_nike_name)
    LinearLayout linearNikeName;
    @BindView(R.id.switchcompat)
    SwitchCompat switchcompat;
    @BindView(R.id.linear_phone1)
    LinearLayout linearPhone1;
    @BindView(R.id.linear_phone2)
    LinearLayout linearPhone2;
    @BindView(R.id.linear_password)
    LinearLayout linearPassword;
    @BindView(R.id.linear_exit)
    LinearLayout linearExit;
    @BindView(R.id.tv_nike_name)
    TextView tvNikeName;
    private String nikeName = "";//昵称
    private boolean messageSelect = false;//消息推送
    private String phone1 = "";//通知手机
    private String phone2 = "";//绑定手机

    @Override
    public boolean isImmersionBarEnabled() {
        return false;
    }

    @Override
    public boolean isSupportSwipeBack() {
        return false;
    }

    @Override
    public int getLayoutResId() {
        return R.layout.activity_user_center;
    }

    @Override
    public void init() {

        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(getResources().getColor(R.color.white));
       /* Uri uri = Uri.parse("https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3103457797,1011040581&fm=26&gp=0.jpg");
        simpleDraweeView.setImageURI(uri);*/
        simpleDraweeView.setImageResource(R.drawable.touxiang);

        switchcompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                messageSelect = isChecked;
            }
        });
    }

    @Override
    public void loadData() {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @PermissionSuccess(requestCode = 100)
    public void doSomething() {
        new MaterialDialog.Builder(UserCenterActivity.this)
                .title("选择来源")
                .items(R.array.photo_resouce)
                .itemsCallback(new MaterialDialog.ListCallback() {
                    @Override
                    public void onSelection(MaterialDialog dialog, View view,
                                            int which, CharSequence text) {
                        switch (which) {
                            case 0:
                                camera();
                                break;
                            case 1:
                                selectImg();
                                break;
                        }
                    }
                })
                .show();
    }

    @PermissionFail(requestCode = 100)
    public void doFailSomething() {
        showToast("请同意相关权限");
    }


    @SuppressLint("ResourceAsColor")
    @OnClick({R.id.linear_back, R.id.linear_head, R.id.linear_nike_name,
            R.id.linear_exit,R.id.linear_phone1,R.id.linear_phone2,R.id.linear_password})
    public void OnClick(View view) {
        switch (view.getId()) {
            //通知手机
            case R.id.linear_phone1:
                Intent intent1 = new Intent(UserCenterActivity.this,NoticePhoneActivity.class);
                intent1.putExtra("type",1);
                startActivity(intent1);
                break;
            //绑定手机
            case R.id.linear_phone2:
                Intent intent2 = new Intent(UserCenterActivity.this,NoticePhoneActivity.class);
                intent2.putExtra("type",2);
                startActivity(intent2);
                break;
            //手机登录密码
            case R.id.linear_password:

                break;
            case R.id.linear_back:
                finish();
                break;
            case R.id.linear_head:
                PermissionGen.needPermission(this, 100,
                        new String[]{
                                Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.CAMERA
                        });
                break;
            case R.id.linear_nike_name:
                new MaterialDialog.Builder(this)
                        .title("标题")
                        .content("输入昵称")
                        //限制输入类型
                        .inputType(InputType.TYPE_CLASS_TEXT)
                        .input("", null, new MaterialDialog.InputCallback() {
                            @Override
                            public void onInput(MaterialDialog dialog, CharSequence input) {
                                if(!TextUtils.isEmpty(input)){
                                    nikeName = input.toString();
                                    tvNikeName.setText(input.toString());
                                }else {
                                    nikeName = "";
                                }
                            }
                        })
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(MaterialDialog dialog, DialogAction which) {

                            }
                        })
                        .positiveText("确定")
                        .positiveColor(UserCenterActivity.this.getResources().getColor(R.color.green))
                        .onNegative(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(MaterialDialog dialog, DialogAction which) {

                            }
                        })
                        .negativeText("取消")
                        .negativeColor(UserCenterActivity.this.getResources().getColor(R.color.green))
                        .show();
                break;
            case R.id.linear_exit:
                new MaterialDialog.Builder(this)
                        .title("确认退出")
                        /*.content("包含输入框的diaolog")
                                .widgetColor(Color.BLUE)//输入框光标的颜色*/
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                AppDroid.getInstance().exitClient();
                            }
                        })
                        .positiveText("确定")
                        .positiveColor(UserCenterActivity.this.getResources().getColor(R.color.green))
                        .onNegative(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            }
                        })
                        .negativeText("取消")
                        .negativeColor(UserCenterActivity.this.getResources().getColor(R.color.green))
                        .show();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onSuccess(int what, InfoResult t) {

    }

    @Override
    protected void onFail(int what, InfoResult t) {

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //相册返回
        if (requestCode == RESULT_CODE_2 && resultCode == RESULT_OK) {

            /**
             * 第三方相册选择
             */
            if (mUris != null && mUris.size() > 0) {
                mUris.clear();
            }
            mUris = Matisse.obtainResult(data);
            if (mUris != null && mUris.size() > 0) {
                File file = new File(getRealFilePath(mUris.get(0)));
                Uri uri = Uri.fromFile(file);
                cropRawPhoto(uri);
            }
        }
        //相机返回
        else if (requestCode == RESULT_CODE_1 && resultCode == RESULT_OK) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                // 调用裁剪方法
                cropRawPhoto(mProviderUri);
            } else {
                cropRawPhoto(mUri);
            }
        } else if (requestCode == UCrop.REQUEST_CROP) {
            if (data != null) {
                Uri croppedFileUri = UCrop.getOutput(data);
                if (croppedFileUri != null) {
                    pathCrop = getRealFilePath(croppedFileUri);
                    Uri uri = Uri.fromFile(new File(pathCrop));
                    simpleDraweeView.setImageURI(uri);
                }
            }

        } else if (requestCode == UCrop.RESULT_ERROR && resultCode == RESULT_OK) {
            showToast(UCrop.getError(data) + "");
            pathCrop = "";
        }
    }

    /**
     * 门店图片
     */
    // 没有截取时的图片路径
    private String pathPhoto = "";
    //截取后的图片路径
    private String pathCrop = "";
    // 7.0 以上的uri
    private Uri mProviderUri;
    // 7.0 以下的uri
    private Uri mUri;
    public static final int RESULT_CODE_1 = 201;

    /**
     * 拍照
     * index 1老板头像 2店铺图像
     */
    private void camera() {
        File file = null;
        FileUtils.getInstance().createPhotoDirectory();
        file = new File(Constants.DEFAULT_PHOTO_IMAGE_DIR, System.currentTimeMillis() + ".png");
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Android7.0以上URI
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //通过FileProvider创建一个content类型的Uri
            mProviderUri = FileProvider.getUriForFile(this, "com.umerclass.fileprovider", file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mProviderUri);//添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {

            mUri = Uri.fromFile(file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
        }
        try {
            startActivityForResult(intent, RESULT_CODE_1);

        } catch (ActivityNotFoundException anf) {
            showToast("摄像头未准备好!");
        }
    }


    /**
     * 相册
     */
    public static final int RESULT_CODE_2 = 202;
    private int flag = 2;//蓝色主题(知乎主题) 2 Dracula主题
    private List<Uri> mUris;//相册选择的图片uri

    private void selectImg() {
        FileUtils.getInstance().createPhotoDirectory();
        //调用系统相册
        /*Intent intent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, RESULT_CODE_2);*/
        Matisse.from(UserCenterActivity.this)
                .choose(MimeType.of(MimeType.JPEG, MimeType.PNG))
                .theme(R.style.Matisse_Dracula)
                .countable(false)
                .maxSelectable(1)
                .imageEngine(new PicassoEngine())
                .forResult(RESULT_CODE_2);
    }

    /**
     * 截取图片
     */
    private void cropRawPhoto(Uri uri) {
        // 修改配置参数（我这里只是列出了部分配置，并不是全部）
        UCrop.Options options = new UCrop.Options();
        options.setToolbarColor(Color.parseColor("#AD1F26"));
        options.setStatusBarColor(Color.parseColor("#AD1F26"));
      /*  options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        // 是否隐藏底部工具
        options.setHideBottomControls(false);
        // 图片格式
        options.setCompressionFormat(Bitmap.CompressFormat.PNG);
        // 设置图片压缩质量
        options.setCompressionQuality(100);
        // 是否让用户调整范围(默认false)，如果开启，可能会造成剪切的图片的长宽比不是设定的
        // 如果不开启，用户不能拖动选框，只能缩放图片
        //options.setFreeStyleCropEnabled(true);*/
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        //设置隐藏底部容器，默认显示
        //options.setHideBottomControls(true);
        //是否能调整裁剪框
        options.setFreeStyleCropEnabled(true);

        // 设置源uri及目标uri
        UCrop.of(uri, Uri.fromFile(new File(Constants.DEFAULT_PHOTO_IMAGE_DIR, System.currentTimeMillis() + ".png")))
                .withAspectRatio(1, 1)
                .withMaxResultSize(200, 200)
                .withOptions(options)
                .start(this);
    }

    /**
     * uri转path
     */
    private String getRealFilePath(final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
